package com.lyh.hkcloud.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;
import com.lyh.hkcloud.R;
import com.lyh.hkcloud.base.BaseActivity;
import com.lyh.hkcloud.constants.HttpUrlComstants;
import com.lyh.hkcloud.util.DownloadUtil;
import com.lyh.hkcloud.util.base.SaveData;
import com.lyh.hkcloud.util.base.ToastUtils;
import com.lyh.hkcloud.util.http.Request;
import com.lyh.hkcloud.util.http.listener.json.JsonFailuredListener;
import com.lyh.hkcloud.util.http.listener.json.JsonSuccessListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * @author: zhongfan
 * @program: hkCloud
 * @description: 首页
 * @company—date: 利元数据 2022-02-10 20:00
 **/
public class HomeActivity extends BaseActivity implements View.OnClickListener {

    private ImageView iv_collecting_assets;
    private TextView  tv_collecting_assets;
    private ImageView iv_borrowed_assets;
    private TextView  tv_borrowed_assets;
    private ImageView iv_transfer_assets;
    private TextView  tv_transfer_assets;
    private ImageView iv_return_of_assets;
    private TextView  tv_return_of_assets;
    private ImageView iv_inventory_management;
    private TextView  tv_inventory_management;
    private ImageView iv_warranty_assets;
    private TextView  tv_warranty_assets;
    private ImageView iv_receiving_consumables;
    private TextView  tv_receiving_consumables;
    private ImageView iv_return_consumables;
    private ImageView iv_area_bind;
    private TextView  tv_area_bind;
    private ImageView iv_requisition_registration;
    private TextView  tv__requisition_registration;
    private TextView  tv_return_consumables;
    private ImageView iv_modify_binding_location;
    private TextView  tv_modify_binding_location;
    private ImageView iv_modify_recipient;
    private TextView  tv_modify_recipient;
    private ImageView iv_cancellation;
    private TextView  tv_check;
    private ImageView iv_check;
    private HomeService service;

    private TextView  tv_scan;
    private ImageView iv_scan;


    private final String TAG = "doDownloadApk";
    private File file;

    @Override
    protected Activity getActivity() {
        return this;
    }

    @Override
    protected void onBeginInit() {
        service = new HomeService(HomeActivity.this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_home;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        iv_collecting_assets = findViewById(R.id.iv_collecting_assets);
        iv_borrowed_assets = findViewById(R.id.iv_borrowed_assets);
        tv_borrowed_assets= findViewById(R.id.tv_borrowed_assets);
        iv_transfer_assets = findViewById(R.id.iv_transfer_assets);
        tv_transfer_assets=findViewById(R.id.tv_transfer_assets);
        iv_return_of_assets = findViewById(R.id.iv_return_of_assets);
        tv_return_of_assets=findViewById(R.id.tv_return_of_assets);
        iv_inventory_management = findViewById(R.id.iv_inventory_management);
        tv_inventory_management=findViewById(R.id.tv_inventory_management);
        tv_collecting_assets=findViewById(R.id.tv_collecting_assets);
        iv_warranty_assets = findViewById(R.id.iv_warranty_assets);
        tv_warranty_assets=findViewById(R.id.tv_warranty_assets);
        iv_receiving_consumables = findViewById(R.id.iv_receiving_consumables);
        tv_receiving_consumables= findViewById(R.id.tv_receiving_consumables);
        iv_return_consumables = findViewById(R.id.iv_return_consumables);
        iv_area_bind= findViewById(R.id.iv_area_bind);
        tv_area_bind= findViewById(R.id.tv_area_bind);
        iv_requisition_registration= findViewById(R.id.iv_requisition_registration);
        tv__requisition_registration= findViewById(R.id.tv__requisition_registration);
        tv_check= findViewById(R.id.tv_check);
        iv_check= findViewById(R.id.iv_check);
        tv_return_consumables=findViewById(R.id.tv_return_consumables);
        iv_modify_binding_location = findViewById(R.id.iv_modify_binding_location);
        tv_modify_binding_location= findViewById(R.id.tv_modify_binding_location);
        iv_modify_recipient = findViewById(R.id.iv_modify_recipient);
        tv_modify_recipient=findViewById(R.id.tv_modify_recipient);
        iv_cancellation = findViewById(R.id.iv_cancellation);
        tv_scan= findViewById(R.id.tv_scan);
        iv_scan= findViewById(R.id.iv_scan);


        iv_collecting_assets.setOnClickListener(this);
        iv_borrowed_assets.setOnClickListener(this);
        iv_transfer_assets.setOnClickListener(this);
        iv_return_of_assets.setOnClickListener(this);
        iv_inventory_management.setOnClickListener(this);
        iv_warranty_assets.setOnClickListener(this);
        iv_receiving_consumables.setOnClickListener(this);
        iv_return_consumables.setOnClickListener(this);
        iv_area_bind.setOnClickListener(this);
        iv_requisition_registration.setOnClickListener(this);
        iv_check.setOnClickListener(this);
        iv_scan.setOnClickListener(this);
        iv_modify_binding_location.setOnClickListener(this);
        iv_modify_recipient.setOnClickListener(this);
        iv_cancellation.setOnClickListener(this);
        getSupportActionBar().hide();
        //导航菜单
        this.getNavigationMenuList();
        //AppService appService = new AppService(getActivity());
        //appService.getApps(new JsonSuccessListener() {@Override public void onRespone(String msg, JSONObject response) {}});
    }

    @Override
    protected void initEvent() {

    }

    @Override
    public void onClick(View v) {
        Intent intent ;
        switch (v.getId()) {
            case R.id.iv_collecting_assets:
                intent = new Intent(HomeActivity.this, com.lyh.hkcloud.module.m1300084.IndexActivity.class);
                HomeActivity.this.startActivity(intent);
                break;
            case R.id.iv_borrowed_assets:
                intent = new Intent(HomeActivity.this, com.lyh.hkcloud.module.m1300023.IndexActivity.class);
                HomeActivity.this.startActivity(intent);
                break;
            case R.id.iv_transfer_assets:
                intent = new Intent(HomeActivity.this, com.lyh.hkcloud.module.m1300035.IndexActivity.class);
                HomeActivity.this.startActivity(intent);
                break;
            case R.id.iv_return_of_assets:
                intent = new Intent(HomeActivity.this, com.lyh.hkcloud.module.m1300024.IndexActivity.class);
                HomeActivity.this.startActivity(intent);
                break;
            case R.id.iv_inventory_management:
                intent = new Intent(HomeActivity.this, com.lyh.hkcloud.module.m1300025.IndexActivity.class);
                HomeActivity.this.startActivity(intent);
                break;
            case R.id.iv_warranty_assets:
                intent = new Intent(HomeActivity.this, com.lyh.hkcloud.module.m1300026.IndexActivity.class);
                HomeActivity.this.startActivity(intent);
                break;
            case R.id.iv_receiving_consumables:
                intent = new Intent(HomeActivity.this, com.lyh.hkcloud.module.m1300030.IndexActivity.class);
                HomeActivity.this.startActivity(intent);
                break;
            case R.id.iv_return_consumables:
                intent = new Intent(HomeActivity.this, com.lyh.hkcloud.module.m1300031.IndexActivity.class);
                HomeActivity.this.startActivity(intent);
                break;
            case R.id.iv_area_bind:
                intent = new Intent(HomeActivity.this, com.lyh.hkcloud.module.m1300088.IndexActivity.class);
                HomeActivity.this.startActivity(intent);
                break;
            case R.id.iv_requisition_registration:
                intent = new Intent(HomeActivity.this, com.lyh.hkcloud.module.m1300092.IndexActivity.class);
                HomeActivity.this.startActivity(intent);
                break;
            case R.id.iv_check:
                intent = new Intent(HomeActivity.this, com.lyh.hkcloud.module.m1300089.IndexActivity.class);
                HomeActivity.this.startActivity(intent);
                break;
            case R.id.iv_scan:
                intent = new Intent(HomeActivity.this, com.lyh.hkcloud.module.m1300093.IndexActivity.class);
                HomeActivity.this.startActivity(intent);
                break;
            case R.id.iv_modify_binding_location:
                intent = new Intent(HomeActivity.this, com.lyh.hkcloud.module.m1300085.IndexActivity.class);
                HomeActivity.this.startActivity(intent);
                break;
            case R.id.iv_modify_recipient:
                intent = new Intent(HomeActivity.this, com.lyh.hkcloud.module.m1300086.IndexActivity.class);
                HomeActivity.this.startActivity(intent);
                break;
            case R.id.iv_cancellation:
                SaveData.putValue(this,"token",null);
                intent = new Intent(HomeActivity.this,LoginActivity.class);
                HomeActivity.this.startActivity(intent);
                break;
        }
    }

    private void getNewVersion() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("softwareCode", "assets_007");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Request.post(this, HttpUrlComstants.DOMAIN_NAME_URL+HttpUrlComstants.NEW_VERSION, jsonObject, new JsonSuccessListener() {
            @RequiresApi(api = Build.VERSION_CODES.P)
            @Override
            public void onRespone(String msg, JSONObject response) {
                if (!"0000".equals(response.optString("code"))) {
                    ToastUtils.makeText(getActivity(),"获取更新包失败"+ response.optString("message"), ToastUtils.LENGTH_SHORT).show();
                } else {
                    JSONObject data = response.optJSONObject("data");
                    if(null==data){
                        Log.e("error","获取更新包失败");
                    }
                    Double serverVersion=data.optDouble("major");
                    String downloadUrl = data.optString("filePath");
                    if(versionCheck(serverVersion)) {
                        showTip(getActivity(),downloadUrl);
                    }
                }
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error","获取更新包失败:"+response.optString("message"));
                ToastUtils.makeText(getActivity(), msg, ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    //新版本检测
    private boolean versionCheck(Double serverVersion) {
        //String serverVersion = "1.0"; //todo 实际目标版本号应向平台查询

        Log.d(TAG, "本地版本 version:" + getVersionCode());
        Log.d(TAG, "最新版本 targetVersion:" + serverVersion);
        if(serverVersion > getVersionCode()) {
            return true;
        } else {
            return false;
        }
    }

    //升级弹窗
    private void showTip(Context context,String downloadUrl) {
        AlertDialog dialog = new AlertDialog.Builder(context).setTitle("升级提示").setMessage("检测到新版本，请升级")
                .setNeutralButton("升级", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        doDownload(downloadUrl);
                    }
                }).show();
        //可选
        dialog.setCanceledOnTouchOutside(false);
        //可选
        dialog.setCancelable(false);
    }

    //下载升级包
    private void doDownload(String downloadUrl) {

        //String downloadUrl = "https://url.lyh.haikuicloud.com/platform-oss/file/anon/preview/open/1481460132742299648/1ca82a51ec05e6576b14de8fdc616d8b/1519588979610091520.apk"; //todo 实际下载地址应向平台查询

        String parentPath = "";
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                parentPath = this.getExternalFilesDir(null).getPath();
            } else {
                parentPath = this.getFilesDir().getPath();
            }
        } catch (Exception e) {
            Log.d(TAG, "下载异常 e:" + e.getMessage());
        }

        Log.d(TAG, "下载路径:" + parentPath);
        file = new File(parentPath, "app-release.apk");
        final String filePath = file.getAbsolutePath();

        //如果已有文件，删除
        if (file.exists()) {
            Log.d(TAG, "删除旧 APK");
            file.delete();
        }

        try {
            DownloadUtil.get().download(downloadUrl, filePath, new DownloadUtil.OnDownloadListener() {
                @Override
                public void onDownloadSuccess() {
                    //成功
                    Log.d(TAG, "下载成功");
                    installApk();
                }

                @Override
                public void onDownloading(int progress) {
                    //进度
                   /* Log.d(TAG, "doDownload download:" + progress +"%");*/
                }

                @Override
                public void onDownloadFailed() {
                    //失败
                    Log.d(TAG, "下载失败");
                }
            });
        } catch (Exception e) {
            Log.d(TAG, "下载异常 e2:" + e.getMessage());
        }
    }

    //安装app
    private void installApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;

        //7.0以上安卓系统安装app需要通过fileProvider（需要在AndroidManifest.xml声明）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            data = FileProvider.getUriForFile(this, getActivity().getApplicationContext().getPackageName() + ".fileProvider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Log.d(TAG,"installApk 7.0data:" + data);
        } else {
            data = Uri.fromFile(file);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Log.d(TAG,"installApk data:" + data);
        }
        /*intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);*/
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        this.startActivity(intent);
        /*android.os.Process.killProcess(android.os.Process.myPid());*/
    }

    //获取软件版本号
    private long getVersionCode() {
        long versionName = 0;
        try {
            versionName = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    //获取导航菜单
    private void getNavigationMenuList() {
        JSONObject jsonObject = new JSONObject();
        try {
            //系统id
            jsonObject.put("id", "1481460132742299648");
            jsonObject.put("sysId", "1481460132742299648");
            jsonObject.put("navigationType", 3);
            jsonObject.put("flag", "false");
            //等待200毫秒，不然报错
            //Thread.sleep(350);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        service.post(jsonObject, HttpUrlComstants.NAVIGATION_MENU_LIST, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                JSONArray data = response.optJSONArray("data");
                if (null == data) {
                    Log.e("error", "获取菜单失败:"+msg);
                    ToastUtils.makeText(HomeActivity.this,"获取菜单失败:"+ msg, ToastUtils.LENGTH_SHORT).show();
                }
                for (int i = 0; i < data.length(); i++) {
                    String url = data.optJSONObject(i).optString("url");
                    //领用资产
                    if ("m1300084".equals(url)) {
                        iv_collecting_assets.setVisibility(View.VISIBLE);
                        tv_collecting_assets.setVisibility(View.VISIBLE);
                    }
                    //借用资产
                    else if ("m1300023".equals(url)) {
                        iv_borrowed_assets.setVisibility(View.VISIBLE);
                        tv_borrowed_assets.setVisibility(View.VISIBLE);
                    }
                    //调拨资产
                    else if ("m1300035".equals(url)) {
                        iv_transfer_assets.setVisibility(View.VISIBLE);
                        tv_transfer_assets.setVisibility(View.VISIBLE);
                    }
                    //退还资产
                    else if ("m1300024".equals(url)) {
                        iv_return_of_assets.setVisibility(View.VISIBLE);
                        tv_return_of_assets.setVisibility(View.VISIBLE);
                    }
                    //创建单据
                    else if ("m1300025".equals(url)) {
                        iv_inventory_management.setVisibility(View.VISIBLE);
                        tv_inventory_management.setVisibility(View.VISIBLE);
                    }
                    //盘点管理
                    else if ("m1300026".equals(url)) {
                        iv_warranty_assets.setVisibility(View.VISIBLE);
                        tv_warranty_assets.setVisibility(View.VISIBLE);
                    }
                    //修改绑定地点
                    else if ("m1300085".equals(url)) {
                        iv_modify_binding_location.setVisibility(View.VISIBLE);
                        tv_modify_binding_location.setVisibility(View.VISIBLE);
                    }
                    //修改接收人
                    else if ("m1300086".equals(url)) {
                        iv_modify_recipient.setVisibility(View.VISIBLE);
                        tv_modify_recipient.setVisibility(View.VISIBLE);
                    }
                    //登记列表
                    else if ("m1300030".equals(url)) {
                        iv_receiving_consumables.setVisibility(View.VISIBLE);
                        tv_receiving_consumables.setVisibility(View.VISIBLE);
                    }
                    //出入厂登记
                    else if ("m1300031".equals(url)) {
                        iv_return_consumables.setVisibility(View.VISIBLE);
                        tv_return_consumables.setVisibility(View.VISIBLE);
                    }
                    //区域绑定
                    else if ("m1300088".equals(url)) {
                        iv_area_bind.setVisibility(View.VISIBLE);
                        tv_area_bind.setVisibility(View.VISIBLE);
                    }
                    //盘点资产
                    else if ("m1300089".equals(url)) {
                        iv_check.setVisibility(View.VISIBLE);
                        tv_check.setVisibility(View.VISIBLE);
                    }
                    //网罩领用登记
                    else if ("m1300092".equals(url)) {
                        iv_requisition_registration.setVisibility(View.VISIBLE);
                        tv__requisition_registration.setVisibility(View.VISIBLE);
                    }
                    //入库扫描
                    else if ("m1300093".equals(url)) {
                        iv_scan.setVisibility(View.VISIBLE);
                        tv_scan.setVisibility(View.VISIBLE);
                    }
                }
                //获取版本
                getNewVersion();
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error","获取菜单失败:"+msg);
                ToastUtils.makeText(HomeActivity.this,"获取菜单失败:"+ msg, ToastUtils.LENGTH_SHORT).show();
            }
        });
    }
}
